package org.example.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.example.springboot.common.page.PageResult;
import org.example.springboot.common.service.impl.BaseServiceImpl;
import org.example.springboot.convert.FmcControlConvert;
import org.example.springboot.dao.FmcBeaconDao;
import org.example.springboot.entity.FmcBeacon;
import org.example.springboot.entity.FmcControl;
import org.example.springboot.query.FmcBeaconQuery;
import org.example.springboot.query.FmcControlQuery;
import org.example.springboot.service.FmcBeaconService;
import org.example.springboot.vo.FmcBeaconVO;
import org.example.springboot.vo.FmcControlVO;
import org.example.springboot.vo.FmcStatusVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * @author Fz
 * @since 1.0.0 2024-08-01
 */
@Service
@AllArgsConstructor
public class FmcBeaconServiceImpl extends BaseServiceImpl<FmcBeaconDao, FmcBeacon> implements FmcBeaconService {

    @Override
    public void saveBeacon(String message) {
        CompletableFuture.runAsync(() -> {
            FmcBeaconVO fmcBeaconVO = JSON.parseObject(message, FmcBeaconVO.class);
            FmcBeacon fmcBeacon = this.getOne(new QueryWrapper<FmcBeacon>().eq("did", fmcBeaconVO.getDevice()));
            FmcBeacon fmcBeacon1 = new FmcBeacon();
            if(null == fmcBeacon){
                fmcBeacon1.setPid(fmcBeaconVO.getProject());
                fmcBeacon1.setDid(fmcBeaconVO.getDevice());
                fmcBeacon1.setBatt(fmcBeaconVO.getBatt());
                fmcBeacon1.setPeriod(fmcBeaconVO.getPeriod());
                Date date = new Date();
                fmcBeacon1.setCtime(date);
                this.save(fmcBeacon1);
            }else{
                BeanUtils.copyProperties(fmcBeaconVO, fmcBeacon1);
                fmcBeacon1.setId(fmcBeacon.getId());
                this.updateById(fmcBeacon1);
            }
        });

    }

    @Override
    public PageResult<FmcBeacon> page(FmcBeaconQuery query) {
        QueryWrapper<FmcBeacon> fmcBeaconQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(query.getDid())){
            fmcBeaconQueryWrapper.like("did", query.getDid());
        }
        IPage<FmcBeacon> page = this.page(query, fmcBeaconQueryWrapper.orderByDesc("id"));
        return new PageResult<>(page.getRecords(), page.getTotal());
    }
}